package com.yvon.boot.common.validation.validator;

import com.google.common.collect.Lists;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import com.yvon.boot.common.validation.annotation.Enum;

/**
 * 枚举值校验注解实现
 *
 * @author : Yvon
 * @since : 2021-06-22
 */
public class EnumValidator implements ConstraintValidator<Enum, Object>, Annotation {
    /**
     * 存具体枚举的值
     */
    private final List<Object> values = Lists.newArrayList();


    @SneakyThrows
    @Override
    public void initialize(Enum constraintAnnotation) {



        Class<?> enumClazz = constraintAnnotation.value();
        Object[] enumConstants = enumClazz.getEnumConstants();
        if (null == enumConstants) {
            return;
        }
        Method method = BeanUtils.findMethod(enumClazz, constraintAnnotation.method());
        if (null == method) {
            throw new RuntimeException("枚举对象中不存在获取值的方法");
        }

        method.setAccessible(true);
        try {
            for (Object enumConstant : enumConstants) {
                values.add(method.invoke(enumConstant));
            }
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException("获取枚举值失败");
        }
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        return null == value || values.contains(value);
    }

    @Override
    public Class<? extends Annotation> annotationType() {
        return null;
    }
}